/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.youmoula.mtsq

import android.app.Application
import android.content.Context
import android.util.Log
//import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.DefaultTab.AlbumsTab.value
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalGraphicsContext
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.youmoula.mtsq.data.Email
import com.youmoula.mtsq.data.Recipe
import com.youmoula.mtsq.data.RecipeList
import com.youmoula.mtsq.flour.FlourKtInDb
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class ReplyHomeViewModel(application: Application) : AndroidViewModel(application) {

    var r: RecipeList =  RecipeList("x", emptyList())
    var TAG:String = ReplyHomeViewModel::class.simpleName.toString()
    // UI state exposed to the UI
    private val _uiState = MutableStateFlow(ReplyHomeUIState())
    val uiState: StateFlow<ReplyHomeUIState> = _uiState
    var ctx:Context = application.applicationContext;

    init {
        initEmailList()
    }

    fun getRecipeList(): ReplyHomeUIState {
        Log.i(TAG, "getRecipeList")
        return uiState.value
    }

    fun getValue() : RecipeList{
        return r;
    }

    fun setValue(value:RecipeList){
        this.r = value;
    }

    private fun initEmailList() {
        Log.i(TAG, "initEmailList")
        //var dbh = FlourKtInDb(context, null);
        var dbh = FlourKtInDb(ctx, null);
        val emails = dbh.getRecipeList(_uiState.value.searchKey).recipeList;// r.recipeList;//  emptyList<Recipe>() // ds.recipeList //  LocalEmailsDataProvider.allEmails
        _uiState.value = ReplyHomeUIState(
            emails = emails,
            selectedEmail = emails.firstOrNull()
        )
    }

    fun setSelectedEmail(emailId: Long) {
        /**
         * We only set isDetailOnlyOpen to true when it's only single pane layout
         */
        Log.i(TAG,"selected email$emailId")
        val email = uiState.value.emails.find { it.id == emailId }
        _uiState.value = _uiState.value.copy(
            selectedEmail = email,
            isDetailOnlyOpen = true
        )
    }

    fun setSelectedEmailx(emailId: Long) {
        /**
         * We only set isDetailOnlyOpen to true when it's only single pane layout
         */
        Log.i(TAG,"selected email$emailId")
        val emailx = uiState.value.emails.find { it.id == emailId  }
        val screen: @Composable () -> Unit = { ReplyEmailDetail(email = emailx){} }

    }

    fun setSearchKey(key:String) {
        /**
         * We only set isDetailOnlyOpen to true when it's only single pane layout
         */
        Log.i(TAG,"selected key$key")
        _uiState.update { it.copy(searchKey = key) }
        var dbh = FlourKtInDb(ctx, null);
        val emails = dbh.getRecipeList(_uiState.value.searchKey).recipeList;// r.recipeList;//  emptyList<Recipe>() // ds.recipeList //  LocalEmailsDataProvider.allEmails
        _uiState.update { it.copy(emails = emails) }
    }

    fun closeDetailScreen() {
        _uiState.value = _uiState
            .value.copy(
                isDetailOnlyOpen = false,
                selectedEmail = _uiState.value.emails.firstOrNull()
            )
    }
}

data class ReplyHomeUIState(
    val emails: List<Recipe> = emptyList(),
    val selectedEmail: Recipe? = null,
    val isDetailOnlyOpen: Boolean = false,
    val loading: Boolean = false,
    var searchKey: String? = null,
    val error: String? = null
)
